package com.ztools.viewbinder;

import android.app.Activity;
import android.view.View;

import com.ztools.viewbinder.annotation.BindView;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by zhangxuehui on 2018/6/8.
 */

public class InjectViewUtils {

    public static void bindContentView(Activity target) {
        Class<?> cls = target.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field != null) {
                BindView bindView = field.getAnnotation(BindView.class);
                if (bindView != null) {
                    int resId = bindView.value();
                    try {
                        Method method = cls.getMethod("findViewById", int.class);
                        View view = (View) method.invoke(target, resId);
                        field.setAccessible(true);
                        field.set(target, view);
                        field.setAccessible(false);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    public static void bindView(Activity target) {
        Class<?> cls = target.getClass();
        View parentView = target.getWindow().getDecorView();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field != null) {
                BindView bindView = field.getAnnotation(BindView.class);
                if (bindView != null) {
                    int resId = bindView.value();
                    try {
//                        Method method = cls.getMethod("findViewById", int.class);
//                        View view = (View) method.invoke(target, resId);
                        View view = parentView.findViewById(resId);
                        field.setAccessible(true);
                        field.set(target, view);
                        field.setAccessible(false);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

//    public static Constructor<? extends Unbind> findConstructorByClass(Class cls){
//        try {
//            Constructor ctor = Constructor
//            return
//        }catch (Exception e){
//            return null;
//        }
//    }
}
